import { constantRoutes } from '@/router';
import config from '@/utils/config';
// 路径
import Admin from '@/layout/admin';
import SubLayout from '@/layout/views/router';
import { categoryList } from "@/request/api/bbs/category";
// 请求用对象
// import {axiosReq} from '@/request/http'

/**
 * 模块：系统system
 */
const system = {
  state: {
    config: config, // 配置文件
    category: [], // 分类
    routes: [], // 菜单路由
    menu: [] // 菜单
  },
  mutations: {
    SET_MENUS: (state, routes) => { // 路由新增
      state.menu = routes;
      state.routes = constantRoutes.concat(routes);
    }
  },
  actions: {
    // 生成路由
    GenerateRoutes({ commit }) {return new Promise(resolve => {
      // TODO
      // // 请求
      // axiosReq({
      //   url: "/sys/menu/all",
      //   data: Object.assign({}),
      // }).then(res => {
      //   // 菜单查询
      //   console.log("GenerateRoutes");
      //   const accessedRoutes = menuJsonToRouter(res.detail);
      //   console.log(accessedRoutes);
      //   accessedRoutes.push({ path: '*', redirect: '/404', hidden: true });
      //   commit('SET_MENUS', accessedRoutes)
      //   resolve(accessedRoutes);
      // })
    })},
  }
}

// 菜单数据转为router
function menuJsonToRouter(menuJson){
  return menuJson.map(menu => {
    var router = {
      path:null,
      component:null,
      meta:{},
      children:[],
      index:null,
    }
    // 路径
    var url = menu.url;
    // 路径配置
    router.index = menu.id + "_" + menu.url;
    router.path = url;
    if(menu.name) router.meta.title = menu.name;
    if(menu.img) router.meta.icon = menu.img;
    // 视图组件
    var component;
    if(menu.children){
      if(menu.parent){
        router.component = SubLayout;
      }else{
        router.component = Admin;
      }
    }else{
      router.component = loadView(url);
    }
    // 子组件
    if(menu.children && menu.children.length > 0){
      router.children = menuJsonToRouter(menu.children);
    }
    return router;
  })
}

// 额外方法
export const loadView = (view) => { // 路由懒加载
  return (resolve) =>  require([`@/layout/views${view}`], resolve)
}
// 出口
export default system
